package com.jams.goodox.widget;

import android.app.Activity;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Rect;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.util.DisplayMetrics;

/**
 * Jin viewPager
 */
public class WrapContentHeightViewPager extends ViewPager {

    public WrapContentHeightViewPager(Context context) {
        super(context);
        this.context = context;
    }

    private Context context;

    public WrapContentHeightViewPager(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.context = context;
    }

    private Activity activity;
    public void initActivity(Activity activity) {
        this.activity = activity;
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);

        // 手机屏幕高度
        DisplayMetrics dm = new DisplayMetrics();
        if (null != activity)
            activity.getWindowManager().getDefaultDisplay().getMetrics(dm);
        int height = dm.heightPixels;

        // statusBarHeight
        Rect frame = new Rect();
        if (null != activity)
            activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
        int statusBarHeight = frame.top;

        // 44dp + 44dp + 1dp
        // 计算得出列表上推需要的最大空间
        heightMeasureSpec = MeasureSpec.makeMeasureSpec((int) (height - convertDpToPixel(context, 89)) - statusBarHeight, MeasureSpec.EXACTLY);
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }

    private float convertDpToPixel(Context context, float dp) {
        Resources resources = context.getResources();
        DisplayMetrics metrics = resources.getDisplayMetrics();
        return dp * (metrics.densityDpi / 160f);
    }
}